<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* VVBINH
* binhvuong@vietnambiz.com
*/
require_once('admin_controller'.EXT);
class Image extends admin_controller
{
	var $data = array();
    function Image()
    {
        parent::admin_controller();
        //$this->load->model('image_model');
        $this->load->library(array('upload','Message','session'));
        $this->load->helper('im');
    }

    function index()
    {
    	//echo $_SESSION['login']['user']."aa";
    	$options    = $this->uri->uri_to_assoc(4);
    	$upload_dir = dirname($_SERVER['SCRIPT_FILENAME']).'/uploads/';
    	$m_folder = $upload_dir.'/u-'.$_SESSION['login']['user'];
        $root       = array();

        if(!is_dir($upload_dir.'/u-'.$_SESSION['login']['user'])) {
            create_dir($upload_dir.'/u-'.$_SESSION['login']['user']);
        }

        if(isset($options['dir'])) {
    		$root = explode(':', $options['dir']);
        	$upload_dir .= implode('/', $root);
        }

        if(!is_dir($upload_dir)) {
            $this->message->add('error', 'This dir not exist !');
        }

    	$data['root']	= $root;
        $data['map']    = directory_map($upload_dir, 1);
        //List Folder
 		$data['list_folder'] = directory_map($m_folder, 1);
        //
        $this->load->view('image/index', $data);
    }

    function upload()
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST')
        {
            $uploadto =  $this->input->post('uploadTo');
            $uploadtodir = dirname($_SERVER['SCRIPT_FILENAME']).'/uploads/u-'.$_SESSION['login']['user'].'/'.$uploadto;
            $choosefolder = false;
        	$uri        = $this->uri->uri_to_assoc(4);
			$upload_dir = dirname($_SERVER['SCRIPT_FILENAME']).'/uploads/u-'.$_SESSION['login']['user'].'/'.date('Y').'/'.date('m');

			if(!empty($uploadto)&&is_dir($uploadtodir)){

				$choosefolder = true;
				$upload_dir = $uploadtodir;
			}

			create_dir($upload_dir);

			$config['upload_path'] 		= $upload_dir;
			$config['allowed_types'] 	= 'gif|jpg|png';

			$this->upload->initialize($config);

			if (!$this->upload->do_upload('art_image')) {
		        $this->message->add('error', $this->upload->display_errors());
			}
			else {
				$img_data = $this->upload->data();
				$new_name = $_SERVER['REQUEST_TIME'].'-'.rand(0,999999).$img_data['file_ext'];

				rename($img_data['full_path'], $img_data['file_path'].$new_name);

				// Create thumb
				$thumb_size 	= thumbs();
				$thumb_lib_dir  = thumbs_lib();

		        include_once ($thumb_lib_dir."ThumbLib.inc.php");

		        $options = array(
				    'resizeUp' 		=> true,
				    'jpegQuality'	=> 88,
		        );

				foreach($thumb_size as $size)
				{
					$thumb_dir  = $upload_dir.'/thumb_'.$size;
					create_dir($thumb_dir);

					$t_size = explode('_', $size);

				    $thumb 	= PhpThumbFactory::create($upload_dir."/".$new_name, $options);

				    $thumb->adaptiveResize($t_size[0] + 5, $t_size[1] + 5);
				    $thumb->cropFromCenter($t_size[0], $t_size[1]);
				    $thumb->save($thumb_dir.'/'.$new_name, 'jpg');
				}

                $this->message->add('success', 'Upload image successful !');

                $uri['dir'] = 'u-'.$_SESSION['login']['user'].':'.date('Y').':'.date('m');
			}
			if($choosefolder==true){
			    $uri['dir'] = 'u-'.$_SESSION['login']['user'].':'.$uploadto;
			   admin_redirect('image/index/'.$this->uri->assoc_to_uri($uri));
			}else{
              admin_redirect('image/index/'.$this->uri->assoc_to_uri($uri));
			}
    	}
    }

    function upload_document()
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST')
        {
            $uri        = $this->uri->uri_to_assoc(4);
            $upload_dir = dirname($_SERVER['SCRIPT_FILENAME']).'/uploads/u-'.$_SESSION['login']['user'].'/document/'.date('Y').'/'.date('m');

            create_dir($upload_dir);

            $config['upload_path']      = $upload_dir;
            $config['allowed_types']    = 'zip|rar|gz|doc|docx|xls|pdf|txt|ppt|pps|rtf';

            $this->upload->initialize($config);

            if (!$this->upload->do_upload('art_document')) {
                $this->message->add('error', $this->upload->display_errors());
            }
            else {
                $file_data = $this->upload->data();
                //$new_name = $_SERVER['REQUEST_TIME'].'-'.rand(0,999999).$img_data['file_ext'];

                $this->message->add('success', 'Upload file successful !');

                $uri['dir'] = 'u-'.$_SESSION['login']['user'].':document:'.date('Y').':'.date('m');
            }

            admin_redirect('image/index/'.$this->uri->assoc_to_uri($uri));
        }
    }

    function delete()
    {
    	if($_SERVER['REQUEST_METHOD'] == 'POST')
    	{
    		$src = $this->input->post('url');
                
    		preg_match('@(.*?)/(u-.*?/[0-9]{4}/[0-9]{2})/([0-9]+\-[0-9]+\.(png|jpg|gif))@is', $src, $match);

    		$upload_dir = dirname($_SERVER['SCRIPT_FILENAME']).'/uploads';
    		$thumb_size = thumbs();

    		foreach($thumb_size as $size) {
    			unlink($upload_dir.$match[2].'/thumb_'.$size.'/'.$match[3]);
    		}

    		unlink($upload_dir.$match[2].'/'.$match[3]);// original image

			die('1');
    	}
    }

    /*
     * Function delete images and thump
     * Create by: ThanhTV
     * Email: thanhtran@vietnambiz.com
     * Date create: Fri, 15/04/2011
     */
    function delete_img()
    {
        $src = $this->input->post('url_img');
        if(file_exists($src) == TRUE)
        {                      
            $thumb_size = thumbs();

            foreach($thumb_size as $size)
            {
                $src_img_source = str_replace('/thumb_139_137',"", $src);
                unlink($src_img_source);
                $src_img = str_replace('/thumb_139_137','/thumb_'.$size, $src);
                unlink($src_img);
            }                        
             die("true");
        }
        else
        {die("File not exits!");}
    }

    function create_dir()
    {
        $this->load->helper('string');
        $dir_name = $this->input->post('dir_name');
        $dir_name = create_ascii_url($dir_name);
        $uri      = $this->uri->uri_to_assoc(4);
        $path     = 'uploads/u-'.$_SESSION['login']['user'].'/'.$dir_name;

        if(is_dir($path)) {
            $this->message->add('error', 'This dir does exist !');
            $uri['dir'] = 'u-'.$_SESSION['login']['user'].':'.$dir_name;
        }
        elseif(mkdir($path)) {
            $this->message->add('success', 'Create dir successful !');
            $uri['dir'] = 'u-'.$_SESSION['login']['user'].':'.$dir_name;
        }
        else {
            $this->message->add('error', 'Can not create dir !');
            $uri['dir'] = 'u-'.$_SESSION['login']['user'];
        }

        admin_redirect('image/index/'.$this->uri->assoc_to_uri($uri));
    }
}